<script setup lang="ts">
import { useRoute } from 'vue-router'
import DrawingCanvas from '../components/DrawingCanvas.vue'
import { assessTypeOptions} from '@/utils/options'
import { reportInfo, reportInfoPro, saveReportImg, saveReportImgPro } from '../api'

// 获取路由实例
const route = useRoute()

// 存储路由参数
const sn = ref('')
const token = ref('')
const version = ref('')

// 绘制状态
const isDrawing = ref(false)
const drawingComplete = ref(false)
const drawingError = ref<string | null>(null)

// API响应数据
const apiData = ref(null)
const apiLoading = ref(false)
const apiError = ref<string | null>(null)

const assessTypeText = ref('')


/**
 * 初始化路由参数
 * 从URL中获取sn、token和version参数
 */
const initRouteParams = () => {
  sn.value = route.query.sn as string || ''
  token.value = route.query.token as string || ''
  version.value = route.query.version as string || ''
  
  console.log('路由参数:', { sn: sn.value, token: token.value, version: version.value })
  
  // 如果参数存在，则调用API
  if (sn.value && token.value && version.value) {
    fetchApiData()
  }
}
/**
 * 根据version参数调用不同的API并自动开始绘制
 * lang版本和pro版本使用不同的接口
 */
const fetchApiData = async () => {
  apiLoading.value = true
  apiError.value = null
  drawingError.value = null
  drawingComplete.value = false
  
  try {
    // 构建请求参数
    const params = {
      sn: sn.value,
      token: token.value
    }
    
    // 根据version选择不同的API接口
    let response
    if (version.value === 'pro') {
      // 调用pro版本API
      response = await reportInfoPro(params)
    } else {
      // 默认调用lang版本API
      response = await reportInfo(params)
    }
    
    apiData.value = response
    assessTypeText.value = assessTypeOptions.filter(item => item.key === response.data.type)[0].value
    console.log(`${version.value}版本API数据:`, response)
    
    // API数据加载成功后自动开始绘制
    isDrawing.value = true
  } catch (error) {
    apiError.value = error instanceof Error ? error.message : '未知错误'
    console.error('API请求错误:', apiError.value)
  } finally {
    apiLoading.value = false
  }
}

/**
 * 处理绘制完成事件
 * @param imageData 绘制完成的图像数据
 */
const handleDrawingComplete = async (imageData: string) => {
  drawingComplete.value = true
  drawingError.value = null
  console.log('绘制完成，图像数据长度:', imageData.length)
  
  // 保存图像数据到服务器
  try {
    // 构建请求参数
    const params = {
      sn: sn.value,
      token: token.value,
      imageData: imageData
    }
    
    // 根据version选择不同的API接口保存图像
    let response
    if (version.value === 'pro') {
      // 调用pro版本API保存图像
      response = await saveReportImgPro(params)
    } else {
      // 默认调用lang版本API保存图像
      response = await saveReportImg(params)
    }
    
    console.log(`${version.value}版本图像保存结果:`, response)
  } catch (error) {
    console.error('图像保存错误:', error instanceof Error ? error.message : '未知错误')
  }
}

/**
 * 处理绘制失败事件
 * @param error 错误信息
 */
const handleDrawingError = (error: string) => {
  drawingComplete.value = false
  drawingError.value = error
  console.error('绘制失败:', error)
}

/**
 * 开始新的绘制
 */
const startNewDrawing = () => {
  drawingComplete.value = false
  drawingError.value = null
  isDrawing.value = true
}



// 组件挂载时初始化路由参数
onMounted(() => {
  initRouteParams()
})
</script>

<template>
  <div class="container mx-auto p-4">
    <h1 class="text-2xl font-bold mb-4">{{ assessTypeText }} 绘图界面</h1>
    <!-- 路由参数信息 -->
    <div class="mb-4 p-4 bg-gray-100 rounded-lg">
      <h2 class="text-lg font-semibold mb-2">路由参数</h2>
      <div class="grid grid-cols-3 gap-4">
        <div>
          <span class="font-medium">SN:</span> {{ sn || '未提供' }}
        </div>
        <div>
          <span class="font-medium">Token:</span> {{ token || '未提供' }}
        </div>
        <div>
          <span class="font-medium">版本:</span> 
          <span :class="{'text-blue-600': version === 'lang', 'text-green-600': version === 'pro'}">
            {{ version || '未提供' }}
          </span>
        </div>
      </div>
    </div>
    
    <!-- API状态 -->
    <div v-if="apiLoading" class="mb-4 p-4 bg-blue-50 rounded-lg">
      <p class="text-blue-700">正在加载API数据...</p>
    </div>
    
    <div v-if="apiError" class="mb-4 p-4 bg-red-50 rounded-lg">
      <p class="text-red-700">API错误: {{ apiError }}</p>
    </div>
    
    <!-- 绘图区域 -->
    <div v-if="apiData" class="border rounded-lg p-4 bg-gray-50">
      <template v-for="(item, index) in apiData.data.list" :key="index">
        <DrawingCanvas 
          @drawing-complete="handleDrawingComplete" 
          @drawing-error="handleDrawingError"
          :version="version"
          :info="item"
          v-if="apiData.data.type === assessTypeOptions[0].key"
        />
      </template>
    </div>
    
    <div v-if="drawingComplete" class="mt-4 p-4 bg-green-100 rounded-lg">
      <p class="text-green-700">绘制完成！</p>
    </div>
    
    <div v-if="drawingError" class="mt-4 p-4 bg-red-100 rounded-lg">
      <p class="text-red-700">绘制失败: {{ drawingError }}</p>
    </div>
  </div>
</template>